<template>
  <div class="patrol-rule">
    <Card :bordered="false">
      <p slot="title"
         class="white">巡查管理 > <span class="select-font">巡河规则</span>
      </p>
      <div>
        <Form :model="formItem"
              class="smallForm">
          <Input v-model="formItem.name"
                 :maxlength="30"
                 style="width:200px;margin-right: 25px;"
                 placeholder="请输入用户名称" />
          <Input v-model="formItem.river_name"
                 :maxlength="30"
                 style="width:200px;"
                 placeholder="请输入河流名称" />
        </Form>
        <Button type="info"
                style="margin-left:25px"
                @click="getData(1)">搜索</Button>
        <Button type="error"
                @click="del1"
                class="pull-right">删除巡河规则</Button>
      </div>
    </Card>
    <div class="">
      <Table @on-selection-change="showSelect"
             :data="logData"
             :columns="logColumns"
             stripe>
        <template slot="files"
                  slot-scope="{row}">
          <div v-if="row.files && row.files.length>0">
            <template v-for="(file,index) in row.files">
              <a :key="index"
                 href="javascript:void(0);" 
                 @click="redirect(file.path)">{{file.filename}}</a>
            </template>
          </div>
          <span v-else>暂无</span>
        </template>
      </Table>
      <Page class="pull-right"
            :total="Page.total"
            :current="Page.current"
            :page-size="Page.pageSize"
            size="small"
            show-total
            @on-change="changePage"></Page>
    </div>
    <Modal title="查看巡河轨迹"
           v-model="visible"
           :mask-closable="false"
           width="800">
      <div id="maps"
           style="width: 100%;height: 500px;"></div>
    </Modal>
    <Modal title="编辑巡河规则"
           v-model="editModal"
           @on-ok="edit"
           @on-cancel="hideModal"
           width="700"
           :mask-closable="false">
      <Form ref="form"
            :model="ruleItem"
            :rules="rules">
        <FormItem label="达标长度"
                  prop="stand_length"
                  style="display:inline-block;width:180px">
          <InputNumber v-model="ruleItem.stand_length"
                       :min="0"
                       placeholder="请输入巡查长度" />
          <label>米</label>
        </FormItem>
        <!-- <div>
          <FormItem label="达标时间"
                    prop="stand_time_minutes"
                    style="display:inline-block;width:170px">
            <InputNumber v-model="ruleItem.stand_time_minutes"
                         :max="59"
                         :min="0"
                         @on-change="changeMinute" />
            <label>分</label>
          </FormItem>
          <FormItem prop="stand_time_seconds"
                    style="display:inline-block">
            <InputNumber v-model="ruleItem.stand_time_seconds"
                         :max="59"
                         :min="0"
                         @on-change="changeSecond" />
            <label>秒</label>
          </FormItem>
        </div> -->
        <div>
          <FormItem label="证明文件"
                    prop="files">
            <Upload ref="JFile"
                    :format="['pdf']"
                    :on-format-error="formatError"
                    :show-upload-list="false"
                    type="drag"
                    :on-success="handleSuccess"
                    :max-size="20480"
                    :on-exceeded-size="handleMaxSize"
                    :action="uploadUrl">
              <div>
                <Icon type="ios-cloud-upload"
                      size="23"
                      style="color: #52A1FD;height: 100%;vertical-align: middle;" />
                <span>上传证明文件（需上传区镇两级盖章后的证明文件，单个文件不能超过20M，只支持PDF附件）</span>
              </div>
            </Upload>
            <div class="file-list">
              <template v-for="(file,index) in fileList">
                <div :key="index"
                     class="file-box">
                  <a :href="file.path"
                     target="_blank">{{file.filename}}</a>
                  <span @click="removeFile(index)">删除</span>
                </div>

              </template>
            </div>
          </FormItem>
        </div>
      </Form>
      <div slot="footer">
        <Button @click="hideModal">取消</Button>
        <Button @click="edit"
                type="primary">保存</Button>
      </div>
    </Modal>
    <del-modal ref="delModal"
               title='巡河规则'
               @del="del"
               :delArr="selectData"
               :url="urlDel"></del-modal>
  </div>
</template>

<script>
import { ajaxPost } from 'global/axios';
import { domain, domain2 } from 'global/setting';
import storage from 'good-storage';
import delModal from 'public/delModal';
import tableDropdown from 'public/tableHeaderDropdown';
export default {
  components: {
    delModal,
  },
  data() {
    return {
      urlLogList: '/syn/rcassess/list',
      urlEdit: '/syn/rcassess/edit',
      urlDel: '/syn/rcassess/del',
      logData: [],
      visible: false,
      logColumns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
        },
        {
          title: '河长名',
          minWidth: 100,
          key: 'realname',
        },
        {
          title: '河流名',
          minWidth: 100,
          key: 'river_name',
        },
        {
          title: '河流编号',
          minWidth: 120,
          key: 'river_no',
        },
        {
          title: '河流长度(km)',
          minWidth: 120,
          render: (h, params) => {
            return h('div', params.row.river.length);
          },
        },
        // {
        //   title: '实际巡查长度(m)',
        //   minWidth: 120,
        //   key: 'patrol_length',
        // },
        {
          title: '达标长度(m)',
          minWidth: 120,
          key: 'stand_length',
        },
        {
          title: '达标时间(m)',
          minWidth: 120,
          render: (h, params) => {
            let { time } = this.changeTime(params.row.stand_time);
            return h('div', time);
          },
        },
        {
          title: '巡河时间',
          minWidth: 120,
          key: 'date_time',
        },

        {
          title: '所属河长办',
          minWidth: 100,
          renderHeader: (h, params) => {
            return h(tableDropdown, {
              props: {
                placement: 'bottom-start',
                showArrow: true,
                content: '所属河长办',
                data: [{ value: 'all', name: '全部' }, ...this.deps],
              },
              on: {
                'on-choosed': data => {
                  if (data !== 'all') {
                    this.formItem.dep = data;
                    this.getData();
                  } else {
                    this.formItem.dep = '';
                    this.getData();
                  }
                },
              },
            });
          },
          render: (h, params) => {
            return h('div', params.row.location.dep_name);
          },
        },
        {
          title: '证明文件',
          slot: 'files',
          width: 100,
        },
        {
          title: '操作',
          minWidth: 180,
          render: (h, params) => {
            let route = h(
              'Button',
              {
                props: {
                  type: 'info',
                  size: 'small',
                },
                style: {
                  marginRight: '5px',
                },
                on: {
                  click: () => {
                    this.showMap(params.row);
                  },
                },
              },
              '查看巡河轨迹'
            );
            let editBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small',
                },
                on: {
                  click: () => {
                    this.editModal = true;
                    let timeData = this.changeTime(params.row.stand_time);

                    this.ruleItem = {
                      stand_length: params.row.stand_length,
                      files: [],
                      _id: params.row._id,
                    };
                  },
                },
              },
              '编辑'
            );
            return h('div', [route, editBtn]);
          },
        },
      ],
      formItem: {
        name: '',
        river_name: '',
        dep: '',
      },
      Page: {
        current: 1,
        pageSize: 13,
        total: 0,
      },
      content: '',
      size: {
        minRows: 2,
      },
      editModal: false,
      ruleItem: {
        stand_length: 0,
        stand_time_minutes: 0,
        stand_time_seconds: 0,
        files: [],
      },
      rules: {
        stand_length: [
          {
            required: true,
            type: 'number',
            message: '达标长度不能为空',
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error('达标长度不能少于0!'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          },
        ],
        stand_time_minutes: [
          {
            required: true,
            type: 'number',
            trigger: 'blur',
          },
        ],
        files: [
          {
            message: '请上传证明文件',
            min: 1,
            required: true,
            type: 'array',
            trigger: 'change',
          },
        ],
      },
      selectData: [],
      deps: [],
      uploadUrl: `${domain}/filemanage/upload?dir=notice&token=${storage.session.get(
        'token'
      )}`,
      fileList: [],
    };
  },
  methods: {
    hideModal() {
      this.$refs.JFile && this.$refs.JFile.clearFiles();
      this.fileList = [];
      this.ruleItem.files = [];
      this.editModal = false;
    },

    removeFile(index) {
      this.$refs.JFile.fileList.splice(index, 1);
      this.ruleItem.files.splice(index, 1);
      this.fileList.splice(index, 1);
    },

    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: `文件太大，不能超过 20M。`,
      });
    },

    handleSuccess({ result }) {
      this.ruleItem.files = [];
      this.fileList = [];
      let fileList = this.$refs.JFile.fileList; // 证明文件上传列表
      if (fileList.length > 1) {
        this.$refs.JFile.fileList.splice(0, 1); // 如果文件超过1个，只保留最后一个
      }
      this.ruleItem.files.push(result.path);
      this.fileList.push(result);
    },

    formatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: `文件格式不正确，请上传PDF格式的图片。`,
      });
    },

    changeMinute() {
      this.ruleItem.stand_time_minutes > 59 &&
        (this.ruleItem.stand_time_minutes = 59);
      this.ruleItem.stand_time_minutes < 0 &&
        (this.ruleItem.stand_time_minutes = 0);
    },
    changeSecond() {
      this.ruleItem.stand_time_seconds > 59 &&
        (this.ruleItem.stand_time_seconds = 59);
      this.ruleItem.stand_time_seconds < 0 &&
        (this.ruleItem.stand_time_seconds = 0);
    },
    getData(page) {
      let params = {
        data: {
          page: page || this.Page.current,
          pageSize: this.Page.pageSize,
          searchValue: {
            realname: `${this.formItem.name}|#|like`,
            river_name: `${this.formItem.river_name}|#|like`,
            'location.dep_name': this.formItem.dep,
          },
          order: {},
          basis: 2,
        },
        url: this.urlLogList,
        token: storage.session.get('token'),
        success: res => {
          this.$Loading.finish();
          this.logData = res.data.result.result;
          this.Page.total = res.data.result.totalSize;
        },
      };
      ajaxPost(params);
    },
    changePage(page) {
      this.Page.current = page;
      this.getData();
    },
    showMap(row) {
      if (row.route === undefined || row.route.length === 0) {
        this.$Message.warning('暂无巡河轨迹');
        return;
      }
      let coordtransform = require('coordtransform');
      let arr = [];
      for (var i = 0; i < row.route.length; i++) {
        let item = row.route[i];
        arr.push(coordtransform.wgs84togcj02(item[0], item[1]));
      }
      this.visible = true;
      let center = new qq.maps.LatLng(arr[0][1], arr[0][0]);
      let map = new qq.maps.Map(document.getElementById('maps'), {
        center,
        zoom: 16,
      });
      let path1 = [];
      for (var i = 0; i < arr.length; i++) {
        path1.push(new qq.maps.LatLng(arr[i][1], arr[i][0]));
      }
      let polyline = new qq.maps.Polyline({
        path: path1,
        strokeColor: '#FF0000',
        strokeWeight: 2,
        editable: false,
        map,
      });
    },
    edit() {
      this.$refs['form'].validate(res => {
        if (res) {
          let params = {
            data: { ...this.ruleItem, files: this.fileList },
            url: this.urlEdit,
            token: storage.session.get('token'),
            success: res => {
              if (res.data.code === '0000') {
                this.$Message.success('修改成功');
                this.hideModal();
                this.getData();
              } else {
                this.$Message.warning(`修改失败${res.data.message}`);
              }
            },
          };
          ajaxPost(params);
        }
      });
    },
    showSelect(data) {
      this.selectData = data; // 把勾选的数组存起来
    },
    del1() {
      if (this.selectData.length > 0) {
        this.$refs.delModal.showModal();
      } else {
        this.$Message.warning('请选择巡河规则');
      }
    },
    changeTime(num) {
      //注意数据为156000等,int型,根据实际情况在改;
      let time = '';
      num /= 1000;
      //毫秒除100变成秒
      let check_h = num / 60 / 60;
      let check_m, check_s;
      //判断小时
      check_h = check_h.toString();
      if (check_h.indexOf('.') != -1) {
        check_h = check_h.substring(0, check_h.indexOf('.'));
        check_h = parseInt(check_h);
        check_m = (num - check_h * 60 * 60) / 60;
        //判断分钟
        check_m = check_m.toString();
        if (check_m.indexOf('.') != -1) {
          check_m = parseInt(check_m);
          check_s = num - check_h * 60 * 60 - check_m * 60;
          //判断秒
          if (check_h == 0) {
            if (check_m == 0) {
              time = `${check_s}秒`;
            } else {
              time = `${check_m}分钟${check_s}秒`;
            }
          } else {
            time = `${check_h}小时${check_m}分钟${check_s}秒`;
          }
        } else {
          if (check_h == 0) {
            time = `${check_m}分钟`;
          } else {
            time = `${check_h}小时${check_m}分钟`;
          }
        }
      } else {
        time = `${check_h}小时`;
      }
      return { time, check_h, check_m, check_s };
    },
    del() {
      this.selectData = [];
      this.getData();
    },
    getDeps() {
      let params = {
        data: {
          fieldName: 'dep_name',
          searchValue: { type: '0', level1: '佛山市河长办' },
          type: 'String',
        },
        url: '/sys/department/distinct',
        token: storage.session.get('token'),
        success: res => {
          res.data.result.map(item => {
            this.deps.push({ value: item, name: item });
          });
        },
      };
      ajaxPost(params);
    },
    redirect(path) { // 查看图片
      let url = domain2 + path.substr(path.indexOf('/data')); // 以前上传地址是绝对地址，现改为相对地址，所以需要处理
      window.open(url);
    }
  },
  mounted() {
    this.getData();
    this.getDeps();
  },
};
</script>

<!--河道综合管理页面-->
<style lang="less">
.patrol-rule {
  margin: 15px;
  #map {
    width: 100%;
    max-height: 100%;
  }
  .icon-btn {
    font-size: 20px;
    color: #555555;
  }
  .smallForm {
    display: inline-block;
  }
  .smallArr {
    width: 15%;
    display: inline-block;
  }
}
</style>

<style lang="less" scope>
.file-list {
  width: 100%;
  padding-left: 70px;
  box-sizing: border-box;
  .file-box {
    display: flex;
    > a,
    > span {
      flex: 0 0 auto;
      display: block;
      height: 30px;
      line-height: 30px;
      font-size: 12px;
    }
    > span {
      margin-left: 20px;
      cursor: pointer;
    }
  }
}
</style>